<template>
    <div>
        <el-row :gutter="4">
            <el-col :span="4">
                <el-autocomplete
                        class="inline-input"
                        prefix-icon="fa fa-search"
                        v-model="keyword.teacherName"
                        :fetch-suggestions="querySearch"
                        placeholder="教师姓名"
                        :trigger-on-focus="false"
                        @keyup.enter.native="initTeacherBase"
                        v-permission="'teacher:base:list'"
                        clearable
                ></el-autocomplete>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" icon="fa fa-search" @click="initTeacherBase"
                           v-permission="'teacher:base:list'"> 搜 索
                </el-button>
            </el-col>

            <el-col :span="4">
                <el-button type="primary" icon="fa fa-plus" @click="handleAdd"
                           v-permission="'teacher:social:service:add'"> 添 加 信 息
                </el-button>
            </el-col>
        </el-row>
        <el-dialog
                v-dialog-drag
                title="新增数据"
                :visible.sync="centerDialogVisible"
                width="60%"
                center
                @close="resetField"
        >
            <el-form ref="form" :rules="rules" :model="data" label-width="80px">
                <el-form-item label="教师名:" label-width="80px" prop="teacherName">
                    <el-autocomplete
                            class="inline-input"
                            prefix-icon="fa fa-search"
                            v-model="data.teacherName"
                            :fetch-suggestions="querySearch"
                            placeholder="教师名"
                            :trigger-on-focus="false"
                            @select="handleSelect"
                            clearable
                    ></el-autocomplete>
                </el-form-item>
                <el-form-item label="教工号:" label-width="80px" prop="teacherCollegeId">
                    <el-input v-model="data.teacherCollegeId" placeholder="教工号" disabled></el-input>
                </el-form-item>
                <el-form-item label="请假开始时间：" label-width="120px" prop="leaveBeginDate">
                    <el-date-picker
                            v-model="data.leaveBeginDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="请假结束时间：" label-width="120px" prop="leaveBeginDate">
                    <el-date-picker
                            v-model="data.leaveEndDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="请假类型：" label-width="100px" prop="leaveBeginDate">
                    <el-select v-model="data.leaveCatatory" placeholder="请假类型">
                        <el-option
                                v-for="item in leaveCatatory"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="请假说明:" label-width="80px">
                    <el-upload
                            ref="upload"
                            drag
                            :headers="fileHeaders"
                            :action="baseURL.concat('file/upload')"
                            name="file"
                            :data="fileDir"
                            :on-success="handleFileUploadSuccess"
                            :on-error="handleFileUploadError"
                            :show-file-list=false
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text"> 拖 拽 或 <em>点 击 上 传 </em></div>
                        <div class="el-upload__tip" slot="tip">建议上传之后浏览 默认不解析 utf-8 以外字符</div>
                    </el-upload>
                </el-form-item>

                <el-form-item label="检查上传文件:" label-width="120px">
                    <el-link v-if="data.leaveDescription" :href="`${baseURL}${fileViewPath}${data.leaveDescription}`"
                             target="_blank">
                        {{ data.leaveDescription | filterFileName }} <i
                            class="el-icon-view el-icon--right"></i>
                    </el-link>
                    <el-tag v-else type="success"> 无 上 传 文 件</el-tag>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAttendanceInfo">确 定</el-button>
            </span>
        </el-dialog>
        <el-row>
            <el-table width="100%" border :data="page.row"
                      @selection-change="handleSelectionChange"
                      @row-dblclick="dbClick"
            >
                <el-table-column type="selection" width="50" align="center"></el-table-column>
                <el-table-column prop="teacherName" label="姓名" align="center" width="160"
                                 fixed="left"></el-table-column>
                <!--      详情信息         -->
                <el-table-column label="详情" align="center" width="80"
                >
                    <template slot-scope="scope">
                        <el-button @click="viewDetails(scope.row)" type="text">查看详情</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="teacherCollegeId" label="教工号" align="center" width="160"></el-table-column>
                <el-table-column prop="teacherGender" label="性别" align="center" width="60"></el-table-column>
                <el-table-column prop="teacherDepartment" label="部门" align="center" width="160"></el-table-column>
                <el-table-column prop="teacherRank" label="职称" align="center" width="160"></el-table-column>
                <el-table-column prop="teacherDegree" label="学位" align="center" width="160"></el-table-column>
                <el-table-column prop="leaveBeginDate" label="请假开始时间" align="center" width="160"></el-table-column>
                <el-table-column prop="leaveEndDate" label="请假结束时间" align="center" width="160"></el-table-column>
                <el-table-column prop="leaveCatatory" label="请假类型" align="center" width="160"></el-table-column>
                <el-table-column prop="leaveDescription" label="请假说明" align="center">
                    <template slot-scope="scope">
                        <el-link v-if="scope.row.leaveDescription" type="primary"
                                 :href="`${baseURL}${fileViewPath}${scope.row.leaveDescription}`"
                                 target="_blank">
                            <i class="fa fa-search" aria-hidden="true"></i>
                            {{ scope.row.leaveDescription | filterFileName }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.row)" icon="fa fa-pencil"
                                   v-permission="'teacher:base:update'"> 修 改
                        </el-button>
                        <el-button type="danger" @click="handleDelete(scope.row)" icon="fa fa-times-rectangle"
                                   v-permission="'teacher:base:delete'"> 删 除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
    </div>
</template>

<script>
    import {
        addTeacherAttendance,
        deleteTeacherAttendance,
        page,
        updateTeacherAttendance
    } from "@/api/modules/teacher/attendance";
    import {form, recommendTeacher} from "@/api/modules/dictionary"
    import moment from 'moment';
    import {mapState} from "vuex";
    import {authKey, baseURL, fileViewPath} from "@/config/constant";
    import {removeFile} from "@/api/modules/comprehensive/policy-document";
    import {deleteTeacherBase, updateTeacherBase} from "@/api/modules/teacher/base";

    export default {
        name: "TeacherAttendance",
        data() {
            return {
                baseURL, fileViewPath,
                keyword: {
                    id: 0,
                    teacherBirthday: '',
                    teacherCollegeId: '',
                    teacherDegree: '',
                    teacherDepartment: '',
                    teacherDescription: '',
                    teacherDiplomas: '',
                    teacherGender: '',
                    teacherGraduateCollege: '',
                    teacherGraduateDate: '',
                    teacherHireDate: '',
                    teacherIdentityId: '',
                    teacherPartyDate: '',
                    teacherInDate: '',
                    teacherJobRank: '',
                    teacherMajor: '',
                    teacherName: '',
                    teacherNation: '',
                    teacherOffice: '',
                    teacherPolitical: '',
                    teacherRank: '',
                    teacherRankDate: '',
                    teacherRetired: '',
                    teacherSituation: '',
                    teacherTel: '',
                    teacherWorkDate: '',
                    leaveReason: '',
                    leaveBeginDate: '',
                    leaveEndDate: '',
                    leaveCatatory: '',
                    leaveDescription: '',
                },
                data: {
                    id: 0,
                    teacherBirthday: '',
                    teacherCollegeId: '',
                    teacherDegree: '',
                    teacherDepartment: '',
                    teacherDescription: '',
                    teacherDiplomas: '',
                    teacherGender: '',
                    teacherGraduateCollege: '',
                    teacherGraduateDate: '',
                    teacherHireDate: '',
                    teacherIdentityId: '',
                    teacherPartyDate: '',
                    teacherInDate: '',
                    teacherJobRank: '',
                    teacherMajor: '',
                    teacherName: '',
                    teacherNation: '',
                    teacherOffice: '',
                    teacherPolitical: '',
                    teacherRank: '',
                    teacherRankDate: '',
                    teacherRetired: '',
                    teacherSituation: '',
                    teacherTel: '',
                    teacherWorkDate: '',
                    leaveReason: '',
                    leaveBeginDate: '',
                    leaveEndDate: '',
                    leaveCatatory: '',
                    leaveDescription: ''
                },
                isAdd:false,
                page: {
                    row: [],
                    total: 0
                },
                pagination: {
                    current: 1,
                    size: 9
                },
                centerDialogVisible: false,
                rules: {
                    teacherName: [{required: true, message: '请输入教师名', trigger: 'blur'}]
                },
                // 推荐信息
                recommend: {
                    teacher: [],
                    form: {}
                },

                leaveCatatory: ["事假", "病假", "产假", "丧假"]
            }
        },

        computed: {
            ...mapState("user", ["userToken"]),
            fileHeaders() {
                // 文件上传携带头信息
                let obj = {};
                obj[authKey] = this.userToken;
                return obj
            },
            fileDir() {
                // 上传的文件位置
                return {dir: "policy"}
            }
        },
        filters: {
            filterFileName(value) {
                // 斜杠位置
                let slashIndex = value.lastIndexOf("/");
                // 文件随机数位置
                let randomIndex = value.indexOf("-");
                return value.slice(slashIndex + 1, randomIndex) + value.slice(value.indexOf('.'));
            }
        },
        methods: {
            initTeacherBase() {
                page(this.pagination, this.keyword).then(response => {
                    this.page.row = response.row;
                    this.page.total = response.total;
                })

            },

            // 删除单个
            handleDelete(row) {
                this.$confirm(`此操作将永久删除 <strong><i> ${row.teacherName} </i></strong> 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    dangerouslyUseHTMLString: true,
                    type: 'warning'
                }).then(() => {
                    deleteTeacherAttendance(row.id).then(() => {
                        // 刷新页面
                        this.initTeacherBase();
                    });
                })

            },

            setImageSrc(image){
                let imageSrc=baseURL+fileViewPath+image
                return imageSrc
            },

            initRecommend() {
                recommendTeacher().then(response => {
                    this.recommend.teacher = response;
                });
                form().then(response => {
                    this.recommend.form = response;
                });
            },

            resetField() {
                // 清空表单验证
                this.$refs.form.resetFields();
            },

            dbClick(row){
                if (row.leaveDescription!=null && row.leaveDescription!=""){
                    let url=this.baseURL+this.fileViewPath+row.leaveDescription
                    window.open(url,"_blank")
                }
                // baseURL}${fileViewPath}${scope.row.leaveDescription

            },

            //时间格式化
            dateFormat:function(row, column) {
                debugger
                var date = row[column.property];
                if (date == undefined) {
                    return "";
                }
                return moment(date).format("YYYY-MM-DD")
            },

            async handleFileUploadSuccess(response) {
                await removeFile(this.data.leaveDescription);
                if (response.code <= 30000 && response.code >= 20000) {
                    this.data.leaveDescription = response.data;
                    this.$message.success({message: response.msg})
                } else {
                    this.$message.error({message: response.msg})
                }
            },
            handleFileUploadError() {
                this.$message.error({message: "上传失败"})
            },

            handleAdd() {
                this.isAdd=true
                Object.assign(this.data, {
                    "id": "",
                    "teacherId": "",
                    "teacherName": "",
                    "teacherGender": "",
                    "teacherDepartment": "",
                    "teacherRank": "",
                    "teacherDegree": "",
                    "teacherCollegeId": "",
                    "serviceYear": "",
                    "serviceDate": "",
                    "serviceCompany": "",
                    "serviceProject": "",
                    "serviceObject": "",
                    "serviceContent": "",
                    "serviceWorkLoad": "",
                    "serviceDescription": "",
                    "leaveReason": '',
                    "leaveBeginDate": '',
                    "leaveEndDate": '',
                    "leaveCatatory": '',
                    "leaveDescription": '',
                });
                this.centerDialogVisible = true;
            },
            // 查询
            querySearch(queryString, cb) {
                cb(this.recommend.teacher.filter(item => item.value.indexOf(queryString) !== -1))
            },
            // 搜索
            handleSelect(data) {
                this.data.teacherCollegeId = data.jobNumber;
                this.data.teacherName = data.value;
                this.data.teacherId = data.id;
            },

            // 修改单个
            handleEdit(row) {
                // 不是添加
                this.isAdd = false;
                alert(JSON.stringify(row))
                Object.assign(this.data, row);
                this.centerDialogVisible = true;
            },

            addAttendanceInfo() {
                //将时间转为时间戳
            // this.data.leaveBeginDate=Date.parse(this.data.leaveBeginDate)
            // this.data.leaveEndDate=Date.parse(this.data.leaveEndDate)

                if (this.isAdd){
                    addTeacherAttendance(this.data).then(() => {
                        this.centerDialogVisible = false
                        this.initTeacherBase()
                    })
                }else {
                    updateTeacherAttendance(this.data).then(() => {
                        // TODO 修改信息 不需要 init
                        this.centerDialogVisible = false;
                        this.initTeacherBase();
                    })
                }

                // this.$refs.from.validate(valid => {
                //     if (valid) {
                //
                //     }
                // })
            }
        },
        mounted() {
            this.initTeacherBase()
            this.initRecommend();
        }
    }
</script>

<style scoped>

</style>